<template>
    <div class="cart">
        <h4>全部商品</h4>
        <div class="cart-main">
            <div class="cart-th">
                <div class="cart-th1">全部</div>
                <div class="cart-th2">商品</div>
                <div class="cart-th3">单价（元）</div>
                <div class="cart-th4">数量</div>
                <div class="cart-th5">小计（元）</div>
                <div class="cart-th6">操作</div>
            </div>
            <div class="cart-body">
                <ul class="cart-list" v-for="cartInfo in cartInfoList" :key="cartInfo.id">
                    <li class="cart-list-con1">
                        <input
                            type="checkbox"
                            name="chk_list"
                            :checked="!!cartInfo.isChecked"
                            @change="btnChecked(cartInfo)"
                        />
                    </li>
                    <li class="cart-list-con2">
                        <img :src="cartInfo.imgUrl" />
                        <div class="item-msg">
                            {{ cartInfo.skuName }}
                        </div>
                    </li>
                    <li class="cart-list-con4">
                        <span class="price">{{ cartInfo.skuPrice }}</span>
                    </li>
                    <li class="cart-list-con5">
                        <a
                            href="javascript:void(0)"
                            class="mins"
                            @click="changeNum('decrement', cartInfo)"
                        >
                            -
                        </a>
                        <input
                            autocomplete="off"
                            type="text"
                            :value="cartInfo.skuNum"
                            minnum="1"
                            class="itxt"
                            @change="changeNum('change', cartInfo, $event)"
                        />
                        <a
                            href="javascript:void(0)"
                            class="plus"
                            @click="changeNum('increment', cartInfo)"
                        >
                            +
                        </a>
                    </li>
                    <li class="cart-list-con6">
                        <span class="sum">{{ cartInfo.skuPrice * cartInfo.skuNum }}</span>
                    </li>
                    <li class="cart-list-con7">
                        <a href="#none" class="sindelet" @click="clearSkuId(cartInfo)">删除</a>
                        <br />
                        <a href="#none">移到收藏</a>
                    </li>
                </ul>
            </div>
        </div>
        <div class="cart-tool">
            <div class="select-all">
                <input class="chooseAll" type="checkbox" v-model="CheckAll" />
                <span>全选</span>
            </div>
            <div class="option">
                <a href="javascript:;" @click="clearCartAll">删除选中的商品</a>
                <a href="#none">移到我的关注</a>
                <a href="#none">清除下柜商品</a>
            </div>
            <div class="money-box">
                <div class="chosed">
                    已选择
                    <span>{{ selectedCount }}</span>
                    件商品
                </div>
                <div class="sumprice">
                    <em>总价（不含运费） ：</em>
                    <i class="summoney">{{ selectedMoney }}</i>
                </div>
                <div class="sumbtn">
                    <router-link class="sum-btn" to="/trade">结算</router-link>
                </div>
            </div>
        </div>
        <!-- 弹出警示框 -->
        <Dialog :visible.sync="isShow">
            <template #herder>
                <h3>提示</h3>
            </template>
            <template>
                <h3>你真的要删除{{ isDelOne ? '这个么' : '这些个么' }}</h3>
            </template>
            <template #footer>
                <div class="btn-footer">
                    <button class="btn-primary" @click="clearOneCart">确认</button>
                    <button @click="isShow = false">取消</button>
                </div>
            </template>
        </Dialog>
    </div>
</template>

<script>
import {
    reqGetShopCartListData,
    reqGetChangeShopCartInfoList,
    reqGetCheckCartListData,
    reqGetOneCartInfoListData,
    reqGetAllCartInfoListData,
    reqGetCartData,
} from '../../api/index';
import { skuNumReg } from '../../utils/reg';
export default {
    name: 'ShopCart',
    data() {
        return {
            cartInfoList: [],
            isShow: false,
            skuId: '',
            isDelOne: false, //删除一条还是删除多条  true为一条  false为多条
            skuIdList: [], // 存储批量删除被选中的商品时的skuId
            leftCartInfoList: [], // 存储剩余未删除的商品
        };
    },
    watch: {
        isShow: {
            handler() {
                if (this.isShow) {
                    document.documentElement.style.overflow = 'hidden';
                } else {
                    document.documentElement.style.overflow = 'auto';
                }
            },
        },
    },
    mounted() {
        // const result = await reqGetShopCartListData();
        // if (result.code === 200) {
        //     this.cartInfoList = result.data[0].cartInfoList;
        // }
        this.getShopCartListData();
    },
    methods: {
        //获取购物车数据
        async getShopCartListData() {
            const result = await reqGetShopCartListData();
            if (result.code === 200) {
                // this.cartInfoList = result.data[0].cartInfoList;
                this.cartInfoList = result.data[0] ? result.data[0].cartInfoList : [];
            } else {
                alert('获取购物车失败');
            }
        },
        //切换商品选择状态，只要状态一发生变化，就会重新发送请求
        async btnChecked(cartInfo) {
            let isChecked = 1 - cartInfo.isChecked;
            const result = await reqGetChangeShopCartInfoList(cartInfo.skuId, isChecked);
            if (result.code === 200) {
                cartInfo.isChecked = isChecked;
            } else {
                alert('修改失败');
            }
        },
        //删除一条商品购物车
        clearSkuId(cartInfo) {
            //弹出对话框
            this.isShow = true;
            //收集要删除的商品ID
            this.skuId = cartInfo.skuId;
            //删除一条数据
            this.isDelOne = true;
        },
        //删除一条商品
        async clearOneCart() {
            let result;
            if (this.isDelOne) {
                //为true删除一条
                result = await reqGetOneCartInfoListData(this.skuId);
            } else {
                //为false删除多条
                result = await reqGetAllCartInfoListData({ data: this.skuIdList });
            }
            if (result.code === 200) {
                this.getShopCartListData();
                this.isShow = false;
            }
        },
        //删除所有商品
        clearCartAll() {
            //清空数据
            this.skuIdList = [];
            this.leftCartInfoList = [];

            this.isShow = true;

            this.cartInfoList.forEach(cartInfo => {
                if (cartInfo.isChecked === 1) {
                    this.skuIdList.push(cartInfo.skuId);
                } else {
                    this.leftCartInfoList.push(cartInfo);
                }
            });

            this.isDelOne = false;
        },
        async changeNum(type, cartInfo, $event) {
            let num = 0;
            let { skuId, skuNum } = cartInfo;
            switch (type) {
                //加
                case 'increment':
                    if (cartInfo.skuNum < 200) {
                        cartInfo.skuNum++;
                        num++; // 这是发给服务器的数量
                    }
                    break;
                //减
                case 'decrement':
                    if (cartInfo.skuNum > 1) {
                        cartInfo.skuNum--;
                        num--; // 这是发给服务器的数量
                    }
                    break;
                case 'change':
                    let newSkuNum = $event.target.value; // 获取用户输入的值
                    let originNum = cartInfo.skuNum; //原来的值
                    if (skuNumReg.test(newSkuNum)) {
                        if (newSkuNum > 200) {
                            cartInfo.skuNum = 200;
                            num = 200 - originNum;
                        } else {
                            num = newSkuNum - cartInfo.skuNum; // 用当前输入的值减去之前值
                            cartInfo.skuNum = newSkuNum; // 重新赋值 让页面看起来是重新输入的值
                        }
                    } else {
                        $event.target.value = originNum;
                    }
                    break;
            }
            if (num === 0) return;
            await reqGetCartData(skuId, skuNum);
        },
    },
    computed: {
        CheckAll: {
            get() {
                // 访问复选框就会执行这个里面的代码
                // 一开始渲染当前购物车组件的时候，应该让全选按钮有一个状态 是不是选中的状态
                // 这个全选按钮是否选中，取决于所有的小按钮状态，只有当所有的小按钮都被选中的，总的这个全选按钮才被选中
                // 如果有一个小按钮不被选中，则这个总按钮也不要被选中
                // every 强调是一个整体 总所有的都满足条件 最终结果 才是true 有一个不满足就是false
                return (
                    this.cartInfoList.length &&
                    this.cartInfoList.every(cartInfo => cartInfo.isChecked === 1)
                );
            },
            async set(value) {
                let isChecked = value ? 1 : 0;
                // 只要一更改，就会执行这里面的代码

                let skuIdList = [];

                this.cartInfoList.forEach(cartInfo => {
                    cartInfo.isChecked = isChecked;
                    // this.btnChecked({ skuId: cartInfo.skuId, isChecked: 1 - isChecked });
                    skuIdList.push(cartInfo.skuId);
                });

                if (!skuIdList.length) return;
                const result = await reqGetCheckCartListData(isChecked, skuIdList);
                if (result.code === 200) {
                    alert('更新成功');
                } else {
                    alert('更新失败');
                }
            },
        },
        //已选商品个数
        selectedCount() {
            return this.cartInfoList.reduce((prev, current) => {
                return prev + current.isChecked;
            }, 0);
        },
        selectedMoney() {
            return this.cartInfoList.reduce((prev, current) => {
                return prev + current.isChecked * current.skuPrice * current.skuNum;
            }, 0);
        },
    },
};
</script>

<style lang="less" scoped>
.cart {
    width: 1200px;
    margin: 0 auto;
    h4 {
        margin: 9px 0;
        font-size: 14px;
        line-height: 21px;
    }
    .cart-main {
        .cart-th {
            background: #f5f5f5;
            border: 1px solid #ddd;
            padding: 10px;
            overflow: hidden;
            & > div {
                float: left;
            }
            .cart-th1 {
                width: 25%;
                input {
                    vertical-align: middle;
                }
                span {
                    vertical-align: middle;
                }
            }
            .cart-th2 {
                width: 25%;
            }
            .cart-th3,
            .cart-th4,
            .cart-th5,
            .cart-th6 {
                width: 12.5%;
            }
        }
        .cart-body {
            margin: 15px 0;
            border: 1px solid #ddd;
            .cart-list {
                padding: 10px;
                border-bottom: 1px solid #ddd;
                overflow: hidden;
                & > li {
                    float: left;
                }
                .cart-list-con1 {
                    width: 15%;
                }
                .cart-list-con2 {
                    width: 35%;
                    img {
                        width: 82px;
                        height: 82px;
                        float: left;
                    }
                    .item-msg {
                        float: left;
                        width: 150px;
                        margin: 0 10px;
                        line-height: 18px;
                    }
                }
                .cart-list-con4 {
                    width: 10%;
                }
                .cart-list-con5 {
                    width: 17%;
                    .mins {
                        border: 1px solid #ddd;
                        border-right: 0;
                        float: left;
                        color: #666;
                        width: 6px;
                        text-align: center;
                        padding: 8px;
                    }
                    input {
                        border: 1px solid #ddd;
                        width: 40px;
                        height: 33px;
                        float: left;
                        text-align: center;
                        font-size: 14px;
                    }

                    .plus {
                        border: 1px solid #ddd;
                        border-left: 0;
                        float: left;
                        color: #666;
                        width: 6px;
                        text-align: center;
                        padding: 8px;
                    }
                }

                .cart-list-con6 {
                    width: 10%;

                    .sum {
                        font-size: 16px;
                    }
                }

                .cart-list-con7 {
                    width: 13%;

                    a {
                        color: #666;
                    }
                }
            }
        }
    }
    .cart-tool {
        overflow: hidden;
        border: 1px solid #ddd;

        .select-all {
            padding: 10px;
            overflow: hidden;
            float: left;

            span {
                vertical-align: middle;
            }

            input {
                vertical-align: middle;
            }
        }

        .option {
            padding: 10px;
            overflow: hidden;
            float: left;

            a {
                float: left;
                padding: 0 10px;
                color: #666;
            }
        }

        .money-box {
            float: right;

            .chosed {
                line-height: 26px;
                float: left;
                padding: 0 10px;
            }

            .sumprice {
                width: 200px;
                line-height: 22px;
                float: left;
                padding: 0 10px;

                .summoney {
                    color: #c81623;
                    font-size: 16px;
                }
            }

            .sumbtn {
                float: right;

                a {
                    display: block;
                    position: relative;
                    width: 96px;
                    height: 52px;
                    line-height: 52px;
                    color: #fff;
                    text-align: center;
                    font-size: 18px;
                    font-family: 'Microsoft YaHei';
                    background: #e1251b;
                    overflow: hidden;
                }
            }
        }
    }
}
</style>
